from django.shortcuts import render

# Create your views here.
import jwt
import random
from rest_framework.views import APIView
from rest_framework.response import Response
import uuid
# from django./
from .ser import *
import base64
import hashlib
from shiyanlou import settings
from django.core.mail import send_mail  # 邮箱
from django.core.cache import cache
import re
from shiyanlou.settings import SECRET_KEY
from .models import *
import itsdangerous


# 随机验证码
def get_random_str():
    code = ''
    code_str = 'abcdefghijklmnopqrstuvwxyz1234567890'
    # 随机生成一个验证码  数字6位
    for k in range(5):
        code += code_str[random.randint(0, 35)]
    return code


#
def md5_md5(params):
    md5 = hashlib.md5(params.encode(encoding='utf8'))
    return md5.hexdigest()


# 发送验证码
class Sendcode(APIView):
    def post(self, request):
        email = request.data.get('email')
        code = get_random_str()
        ret = '您的验证码是:{}'.format(code)
        my_email = send_mail('激活验证', ret, settings.DEFAULT_FROM_EMAIL, [email])
        if not my_email == 1:
            return Response({'code': 0, 'msg': "邮件发送失败", })
        key = 'syl_' + email
        cache.set(key, code, 30)
        return Response({'code': 200, 'msg': "邮件发送成功", 'ma': code})


# 注册
class Registerview(APIView):
    def post(self, request):
        email = request.data.get('register_email')  # 获取前段邮箱
        password = request.data.get('register_passwd')  # 获取前段邮箱
        code = request.data.get('register_verify')  # 获取前段的验证码
        re_email = r'(\w+)@(\w+)\.(\w+)'  # 验证邮箱的格式
        if not re.match(re_email, email):
            return Response({'code': 401, 'msg': '邮箱格式错误'})
            # 获取是否输入了验证码
        if not code:
            return Response({'code': 406, 'msg': '请输入验证码'})
        code_ = cache.get('syl_' + email)
        if not code_:
            return Response({'code': 406, 'msg': '验证码失效'})
        if code == code_:
            user_ = User.objects.filter(email=email).first()
            if user_:
                return Response({'code': 405, 'msg': '用户名已存在'})
            else:
                User.objects.create(email=email, username=email, password=password)
                return Response({'code': 200, 'msg': '注册成功'})
        else:
            return Response({'code': 4004, 'msg': '验证码错误'})


# cookie私有化
'''



class index(APIView):
    def get(self, request):
        request.session['uuid'] = str(uuid.uuid1())
        return Response({'code': 200})


set = itsdangerous.TimedJSONWebSignatureSerializer('jagijg', expires_in=600, )


class Cet(APIView):
    def post(self, request):
        email = request.data.get('email')
        uuid = request.session.get('uuid')
        data = {'uuid': uuid, 'email': email}
        token = set.dumps(data).decode()
        url = 'http://127.0.0.1:8080?token=' + token
        return Response({'url': url})


class CheckToken(APIView):
    def post(self, request):
        token = request.data.get('token')
        uuid = request.session.get('uuid')
        try:
            data = set.loads(token)
            if data['uuid'] == uuid:
                return Response({'code': '200'})
        except Exception as e:
            print(e)
            return Response({'code': 400})
'''


# 登录
class loginview(APIView):
    def post(self, request):
        email = request.data.get('login_email')
        password = request.data.get('login_passwd')
        print(email, password)
        user_obj = User.objects.filter(email=email).first()
        if user_obj:
            if user_obj.password == password:
                info = {
                    'uid': user_obj.id,
                    'email': user_obj.email
                }
                token = jwt.encode(info, SECRET_KEY)
                return Response(
                    {'code': 200, 'msg': '登录成功', 'token': token, 'uid': user_obj.id, 'username': user_obj.username,
                     'email': user_obj.email})
            else:
                return Response({'code': 400, 'msg': '登录失败,密码错误'})
        else:
            return Response({'code': 400, 'msg': '没有此用户，可以注册'})


# 用户展示
class Usershow(APIView):
    def get(self, request):
        # email = request.GET.get('email')
        uid = request.GET.get('uid')
        print(uid)
        suo = User.objects.filter(id=uid)
        ser = Userser(suo, many=True)
        return Response(ser.data)


# 找回密码：
class zhaohui(APIView):
    def post(self, request):
        email = request.data.get('email')
        code = request.data.get('code')
        re_email = r'(\w+)@(\w+)\.(\w+)'  # 验证邮箱的格式
        if not re.match(re_email, email):
            return Response({'code': 401, 'msg': '邮箱格式错误'})
            # 获取是否输入了验证码
        if not code:
            return Response({'code': 406, 'msg': '请输入验证码'})
        code_ = cache.get('syl_' + email)
        if not code_:
            return Response({'code': 406, 'msg': '验证码失效'})
        if code == code_:

            password = request.data.get('password')
            password1 = request.data.get('password1')
            if password == password1:
                user = User.objects.filter(email=email).first()
                user.password = password1
                user.save()
                return Response({'msg': '修改成功', 'code': 200})
            else:
                return Response({'msg': '输入的两次密码错误', 'code': 400})


# 课程分类
class kechengcateshow(APIView):
    def get(self, request):
        suo = coursecate.objects.all()
        ser = coursecateser(suo, many=True)
        return Response(ser.data)


# 课程标签
class kechengbiaoshow(APIView):
    def get(self, request):
        uid = request.GET.get('uid')
        # print(uid)
        suo = coursebiao.objects.filter(course_id=uid)
        ser = coursebiaoser(suo, many=True)
        return Response(ser.data)


# 添加课程,展示详情
class coureseniu(APIView):
    def post(self, request):
        '''
        title = models.CharField(max_length=255)  # 标题
    desc = models.CharField(max_length=255)  # 简介
    author = models.CharField(max_length=255)  # 作者
    price = models.CharField(max_length=255)  # 价格
    is_online = models.IntegerField(default=0)  # 是否上线,未上线0，上线是1
    pic = models.ImageField(upload_to='static/img')  # 图片
    flow = models.IntegerField(null=True)  # 关注
    read = models.IntegerField(null=True)  # 阅读
    type = models.IntegerField()  # 课程类型   免费1会员2训练营3
    createtime = models.DateTimeField(auto_now_add=True)  # 上线时间
    tags_id = models.ForeignKey(coursebiao, on_delete=models.CASCADE)  # 课程标签
        '''
        ser = Courseniuser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '添加成功'})
        else:
            return Response({'code': 400, 'msg': ser.errors})

    def get(self, request):
        uid = request.GET.get('uid')
        print(uid)
        # uid = int(uid)
        suo = Courseniu.objects.filter(tags_id_id=uid)
        # suo = Courseniu.objects.all()
        ser = Courseniuser(suo, many=True)
        return Response(ser.data)


